Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

rttc

Package Overview
Dependencies
Maintainers
4
Versions
108
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

rttc

Runtime type-checking for JavaScript.

  • 3.4.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
40K
decreased by-42.81%
Maintainers
4
Weekly downloads
 
Created
Source

rttc

Runtime (recursive) type-checking for JavaScript.

Installation

$ npm install rttc --save

Quick Start

var rttc = require('rttc');

rttc.coerce({ firstName: 'string'}, {firstName: 45});
// => { firstName: "45" }

rttc.coerce({ firstName: 'string'}, {something: 'totally incorrect'});
// => { firstName: "" }
// (when confronted with something totally weird, `.coerce()` returns the "base value" for the type)

rttc.validate({ firstName: 'string'}, {something: 'totally incorrect'});
// throws error

rttc.validate({ firstName: 'string'}, {firstName: 45});
// => "45"
// (when confronted with minor differences, `.validate()` coerces as needed to make stuff fit)

rttc.validateStrict({ firstName: 'string'}, {firstName: 45});
// throws error
// (`.validateStrict()` demands a value that is precisely the correct type)

rttc.validateStrict({ firstName: 'string'}, {firstName: '45'});
// does not throw, returns undefined

Philosophy

All of the validation and coercion strategies used in this modules are recursive through the keys of plain old JavaScript objects and the indices of arrays.

Coercion vs. Validation
  • .validateStrict() throws if the provided value is not the right type (recursive).
  • .validate() either returns a (potentially "lightly" coerced) version of the value that was accepted, or it throws. The "lightly" coerced value turns "3" into 3, "true" into true, -4.5 into "-4.5", etc.
  • .coerce() ALWAYS returns an acceptable version of the value, even if it has to mangle it to get there (i.e. by using the "base value" for the expected type.)
Base values
  • For "string", base value is ""
  • For "number", base value is 0
  • For "boolean", base value is false
  • For any "dictionary" ({}), base value is {}, with whatever keys are expected (recursive)
  • For a generic "array" ([]), base value is [], with a single archetypal item matching the expectation (recursive)
  • For "*", base value is "undefined".

Types

Strings

example: 'stuff'

Numbers

example: 323

Booleans

example: {}

Generic dictionaries

example: {}

The generic dictionary type is a dictionary type schema with no keys.

Dictionaries that have been validated/coerced against the generic dictionary type:

  • will have no prototypal properties, getters, or setters, as well as a complete deficit of any other sort of deceit, lies, or magic
  • are guaranteed to be JSON-serializable, with a few additional affordances:
    • normally, stringified JSON may contain null values. Instead, rttc removes null items from arrays and removes keys with null values from objects.
    • normally, Error instances get stringified into empty objects. Instead, rttc turns them into human-readable strings by reducing them to their .stack property (this includes the error message and the stack trace w/ line numbers)
    • normally, RegExp instances get stringified into empty objects. Instead, rttc turns them into human-readable strings like '/some regexp/gi'
    • normally, function() instances get stringified into empty objects. Instead, rttc turns them into human-readable strings like 'function doStuff (a,b) { console.log(\'wow I can actually read this!\'); }'
Faceted dictionaries

example: {...}

The faceted dictionary type is any dictionary type schema with at least one key. Extra keys in the actual value that are not in the type schema will be stripped out.

Dictionary type schemas (i.e. plain old JavaScript objects nested like {a:{}}) can be infinitely nested. Type validation and coercion will proceed through the nested objects recursively.

{
  id: 'number',
  name: 'string',
  isAdmin: 'boolean',
  mom: {
    id: 'number',
    name: 'string',
    occupation: {
      title: 'string',
      workplace: 'string'
    }
  }
}
Generic arrays

example: []

Arrays that have been validated/coerced against the generic array type:

  • may be heterogeneous (have items with different types) - but it is generally best practice to avoid heterogeneous arrays in general.
  • are guaranteed to be JSON-serializable, with a few additional affordances:
    • normally, stringified JSON may contain null values. Instead, rttc removes null items from arrays and removes keys with null values from objects.
    • normally, Error instances get stringified into empty objects. Instead, rttc turns them into human-readable strings by reducing them to their .stack property (this includes the error message and the stack trace w/ line numbers)
    • normally, RegExp instances get stringified into empty objects. Instead, rttc turns them into human-readable strings like '/some regexp/gi'
    • normally, function() instances get stringified into empty objects. Instead, rttc turns them into human-readable strings like 'function doStuff (a,b) { console.log(\'wow I can actually read this!\'); }'
Homogeneous arrays

example: ['Margaret'] example: [123] example: [true] example: [[...]] example: [{...}]

Array type schemas may be infinitely nested and combined with dictionaries or any other types.

Runtime arrays being validated/coerced against array type schemas will be homogeneous (meaning every item in the array will have the same type).

Also note that, because of this, when providing a type schema or type-inference-able example for an array, you only need to provide one item in the array, e.g.:

[
  {
    id: 'number',
    name: 'string',
    email: 'string',
    age: 'number',
    isAdmin: 'boolean',
    favoriteColors: ['string'],
    friends: [
      {
        id: 'number',
        name: 'string'
      }
    ]
  }
]
Wildcards

example: '*'

This special type allows anything except undefined. It also does not rebuild objects, which means it maintains the original reference (i.e. is ===). It also does not guarantee JSON-serializability.

Edge cases
  • undefined is never valid as a top-level value, but it is allowed as an item or value in a nested array or dictionary validated/coerced against example: *.
  • null is only valid against example: '*'.
  • NaN is only valid against example: '*'.
  • Infinity is only valid against example: '*'.
  • -Infinity is only valid against example: '*'.
  • -0 is understood as 0
  • +0 is understood as 0

Examples

rttc.infer(value)

Infer the type/schema of the provided value.

require('rttc').infer(false);
// => 'boolean'
require('rttc').infer(0);
// => 'number'
require('rttc').infer({
  foo: 'bar'
});
// => { foo: 'string' }
require('rttc').infer({
  foo: 'whatever',
  bar: { baz: true }
});
// => { foo: 'string', bar: { baz: 'boolean' } }
require('rttc').infer([{
  foo: ['bar']
}]);
// => [{ foo: ['string'] }]
require('rttc').infer({
  user: {
    friends: [{
      name: 'Lenny',
      age: 77
    }]
});
// =>
/*
{
  user: {
    friends: [{
      name: 'Lenny',
      age: 77
    }]
}
*/
rttc.validate(expected, actual)
rttc.validate('string', 'foo');
// => 'foo'

rttc.validate('number', 4.5);
// => 4.5

rttc.validate('boolean', true);
// => true

rttc.validate('string', -2);
// => '-2'

rttc.validate('string', false);
// => 'false'

rttc.validate('number', '3');
// => 3

rttc.validate('boolean', 'true');
// => true

rttc.validate({
  user: {
    friends: [{
      name: 'Lenny',
      age: 77
    }]
}, {
  user: {
    friends: [{
      name: 'Lenny',
      age: '77'
    }]
  }
});
// =>
/*
{
  user: {
    friends: [{
      name: 'Lenny',
      age: 77
    }]
  }
}
 */

If value cannot be properly coerced, throws error with code=E_INVALID_TYPE:

rttc.validate('number', 'asdf');
// throws E_INVALID_TYPE
rttc.coerce(expected, actual)
rttc.coerce('string', 'foo');
// => 'foo'

rttc.coerce('number', 4.5);
// => 4.5

rttc.coerce('boolean', true);
// => true

rttc.coerce('string', -2);
// => '-2'

rttc.coerce('string', false);
// => 'false'

rttc.coerce('number', '3');
// => 3

rttc.coerce('boolean', 'true');
// => true

If value can't be properly coerced, the "base value" for the type will be used:

rttc.coerce('number', 'asdf');
// => 0

rttc.coerce('boolean', 'asdf');
// => false

rttc.coerce({
  user: {
    friends: [{
      name: 'Lenny',
      age: 77
    }]
}, 'err... some dude who\'s friends with lenny?');
// =>
/*
{
  user: {
    friends: [{
      name: 'Lenny',
      age: 77
    }]
  }
}
 */

Keywords

FAQs

Package last updated on 24 May 2015

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc